/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.worker.ui.async.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JOptionPane;

import org.ourgrid.common.ui.AbstractInputFieldsPanel;
import org.ourgrid.common.ui.InputFieldsUI;
import org.ourgrid.common.ui.OurGridUIModel;
import org.ourgrid.common.ui.gui.CommuneDetectionDelaySettingsPanel;
import org.ourgrid.common.ui.gui.CommuneSettingsPanel;
import org.ourgrid.peer.ui.async.model.PeerAsyncUIModel;
import org.ourgrid.worker.ui.async.client.WorkerAsyncInitializer;

public class WorkerConfigurationPanel extends AbstractInputFieldsPanel implements InputFieldsUI {
    

	private static final long serialVersionUID = 1L;
	private CommuneDetectionDelaySettingsPanel fdPanel;
	private WorkerAsyncInitializer workerInitializer;
	
	private static final String WORKERGUI_PROPERTIES = "worker.properties";
	
	/** Creates new form WorkerConfigurationPanel */
    public WorkerConfigurationPanel(OurGridUIModel model) {
    	super(model);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     * @param model 
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    protected void initComponents() {

        tabs = new javax.swing.JTabbedPane();
        basicWorkerConfigurationPanel = new WorkerBasicSettingsPanel(model);
        communePanel = new CommuneSettingsPanel(model);
        fdPanel = new CommuneDetectionDelaySettingsPanel(model);
//        try {
//        	logSettingsPanel = new org.ourgrid.common.ui.gui.LogSettingsPanel(model, controller);
//		} catch (FileNotFoundException e1) {
//			JOptionPane.showMessageDialog(this, "Log properties file was not found, log settings panel will not be available.", "Warning", JOptionPane.WARNING_MESSAGE);
//		} catch (IOException e1) {
//			JOptionPane.showMessageDialog(this, "Error while loading log properties file, log settings panel will not be available.", "Warning", JOptionPane.WARNING_MESSAGE);		
//		}
        restoreDefaultsButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        basicWorkerConfigurationPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Basic Settings"));

        tabs.addTab("Basic", basicWorkerConfigurationPanel);

        tabs.addTab("Commune", communePanel);

        tabs.addTab("Failure Detection", fdPanel);
        
        if (logSettingsPanel != null) {
        	logSettingsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Logging settings"));
        	logSettingsPanel.setPreferredSize(new java.awt.Dimension(200, 100));
        	tabs.addTab("Log", logSettingsPanel);
        }

        restoreDefaultsButton.setText("Restore defaults");
        restoreDefaultsButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				restoreButtonActionPerformed(e);
			}
        	
        });

        saveButton.setText("Save");
        saveButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				saveButtonActionPerformed(e);
			}
        	
        });
        
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(saveButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(restoreDefaultsButton)
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, tabs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 794, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(tabs)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(restoreDefaultsButton)
                    .add(saveButton))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private WorkerBasicSettingsPanel basicWorkerConfigurationPanel;
    private CommuneSettingsPanel communePanel;
    private org.ourgrid.common.ui.gui.LogSettingsPanel logSettingsPanel;
    private javax.swing.JButton restoreDefaultsButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JTabbedPane tabs;
    // End of variables declaration//GEN-END:variables

	/**
	 * Save the inputs of the internal panels.
	 */
    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
		try {
			saveFieldInputs();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    private void restoreButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	try {
    		workerInitializer.getComponentClient().restoreDefaultPropertiesValues();
    		this.initFields();
    	} catch (IOException e) {
    		//TODO - What should be done here?
    	}
    }

    /**
     * Save the current properties of the PeerAsyncComponentClient.
     * @see PeerAsyncUIModel.saveProperties
     */
	private void saveProperties() {
		try {
			model.saveProperties();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), 
					"IO Error" , JOptionPane.ERROR_MESSAGE);
		} finally {
			model.loadProperties();
		}
	}

	/**
	 * Initializes the textFields of the internal panels.
	 */
	public void initFields() throws IOException {
		basicWorkerConfigurationPanel.initFields();

		communePanel.initFields();

		fdPanel.initFields();
		
		if (logSettingsPanel != null) {
			logSettingsPanel.initFields();
		}
	}

	/**
	 * Save the values of the internal panels field inputs.
	 */
	public void saveFieldInputs() throws IOException {
		basicWorkerConfigurationPanel.saveFieldInputs();

		communePanel.saveFieldInputs();

		fdPanel.saveFieldInputs();
		
		if (logSettingsPanel != null) {
			logSettingsPanel.saveFieldInputs();
		}
		
		saveProperties();
	}
	
    /**
     * Disable the editable components of the internal panels.
     */
	public void disableInput() {
		basicWorkerConfigurationPanel.disableInput();
		communePanel.disableInput();
		fdPanel.disableInput();
		if (logSettingsPanel != null) {
			logSettingsPanel.disableInput();
		}
		saveButton.setEnabled(false);
		restoreDefaultsButton.setEnabled(false);
	}

    /**
     * Enable the editable components of the internal panels.
     */
	public void enableInput() {
		basicWorkerConfigurationPanel.enableInput();
		communePanel.enableInput();
		fdPanel.enableInput();
		if (logSettingsPanel != null) {
			logSettingsPanel.enableInput();
		}
		saveButton.setEnabled(true);
		restoreDefaultsButton.setEnabled(true);
		
	}
    
}
